package com.zhang.gmall.realtime.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CaseFormat;
import com.zhang.gmall.realtime.bean.TableProcess;
import com.zhang.gmall.realtime.common.GmallConfig;
import javafx.scene.input.Mnemonic;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @title: jdbc工具类
 * @author: zhang
 * @date: 2022/1/3 15:34
 */
public class JdbcUtil {


    public static <T> List<T> queryList(Connection connection, String querySql, Class<T> clz, boolean underScoreToCamel) throws Exception {
        // 创建集合用于存放查询结果数据
        ArrayList<T> resultList = new ArrayList<>();

        //预编译sql
        PreparedStatement preparedStatement = connection.prepareStatement(querySql);

        //执行查询
        ResultSet resultSet = preparedStatement.executeQuery();

        //解析resultSet
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        while (resultSet.next()){
          //创建范型对象
            T t = clz.newInstance();

            for (int i = 1; i < columnCount + 1; i++) {

                //获取列名
                String columnName = metaData.getColumnName(i);

                //判断是否需要转换为驼峰命名
                if (underScoreToCamel){
                    columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,columnName.toLowerCase());
                }
                //获取列值
                Object value = resultSet.getObject(i);

                //给范型对象赋值
                BeanUtils.setProperty(t,columnName,value);
            }

            resultList.add(t);
        }
        preparedStatement.close();
        resultSet.close();
        //返回结果集
        return resultList;
    }

    public static void main(String[] args) throws Exception {
       /* Class.forName(GmallConfig.PHOENIX_DRIVER);
        Connection connection = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER);
        List<JSONObject> jsonObjects = queryList(connection, "select * from GMALL_REALTIME.DIM_USER_INFO",
                JSONObject.class, true);

        for (JSONObject jsonObject : jsonObjects) {
            System.out.println(jsonObject);
        }*/

        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://hadoop302:3306/gmall_realtime","root","000000");

        List<TableProcess> tableProcesses = queryList(connection, "select * from gmall_realtime.table_process", TableProcess.class, true);

        for (TableProcess tableProcess : tableProcesses) {
            System.out.println(tableProcess);
        }



    }
}
